#region License
// /* **************************************************************
// * Copyright (C) intex Consulting GmbH - All Rights Reserved    *
// *--------------------------------------------------------------*
// * Unauthorized copying of this file, via any medium is         *
// * strictly prohibited                                          *
// *--------------------------------------------------------------*
// * Proprietary and confidential                                 *
// *--------------------------------------------------------------*
// * Dissasembling/modifications strictly prohibited!             *
// ***************************************************************/
#endregion

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using ComHlp.ContentClasses.VirtualControls;
using ComHlp.Exceptions;

namespace ComHlp.Classes.Parser
{
    /// <summary> intex protocol parse helper </summary>
    public static class ParseHelper
    {
        /// <summary> Extract string in passed length from passed sbContent, checking that
        /// total bytes do not exceed fieldLength </summary>
        /// <param name="fieldLength"></param>
        /// <param name="sbContent"></param>
        /// <param name="cutParsed"></param>
        /// <returns></returns>
        public static string ExtractUtf8(int fieldLength, StringBuilder sbContent, bool cutParsed)
        {
            if(ComStatics.SafeUtf8)
                sbContent.Replace((char)65533, ' ');

            string content = sbContent.ToString(0, fieldLength > sbContent.Length ? sbContent.Length : fieldLength);
            int tmpFieldLength = fieldLength;

            if (sbContent.Length < tmpFieldLength)
                tmpFieldLength = sbContent.Length;

            int byteCount = ComStatics.Encoder.GetByteCount(content);
            if (byteCount > fieldLength)
            {
                // we already noticed that we got more bytes than we should... so we try cutting one char less
                while (byteCount > fieldLength)
                {
                    if (tmpFieldLength < 1)
                        throw new CommunicationException($"Byte parsing problem with: {sbContent}");
                    
                    content = sbContent.ToString(0, --tmpFieldLength);
                    // re-check bytecount
                    byteCount = ComStatics.Encoder.GetByteCount(content);
                }
            }
            // cut
            if(cutParsed)
                sbContent.Remove(0, tmpFieldLength > sbContent.Length ? sbContent.Length : tmpFieldLength);
            return content;
        }

        /// <summary> Convert char to int </summary>
        /// <param name="recv"></param>
        /// <returns></returns>
        internal static int Char2Int(char recv)
        {
            return Convert.ToInt32(recv);
        }

        /// <summary> convert string to int </summary>
        /// <param name="string2Parse"></param>
        /// <returns></returns>
        public static int String2Int(string string2Parse)
        {   // remove leading 0
            string2Parse = string2Parse.Trim();
            string2Parse = string2Parse.TrimStart('0');

            if (string2Parse.Length == 0)
                return 0;

            int parsedInt;
            return !int.TryParse(string2Parse, out parsedInt) ? 0 : parsedInt;
        }

        /// <summary> convert string to int </summary>
        /// <param name="string2Parse"></param>
        /// <param name="preComma"></param>
        /// <param name="postComma"></param>
        /// <returns></returns>
        public static double String2Double(string string2Parse, int preComma, int postComma)
        {   
            // build target string
            string2Parse = $"{string2Parse.Substring(0,preComma)},{string2Parse.Substring(preComma, postComma)}";
            
            // remove leading 0
            string2Parse = string2Parse.Trim();
            string2Parse = string2Parse.TrimStart('0');

            if (string2Parse.Length == 0)
                return 0;

            double parsedDouble;
            return !double.TryParse(string2Parse, out parsedDouble) ? 0 : parsedDouble;
        }

        /// <summary> convert string to date in format of yyyyMMdd </summary>
        /// <param name="string2Parse"></param>
        /// <returns></returns>
        internal static DateTime String2Date(string string2Parse)
        {   
            // remove leading 0
            string2Parse = string2Parse.Trim();
            if (string2Parse.Length < 8)
                return DateTime.MinValue;

            DateTime parsedDate;
            if(!DateTime.TryParseExact(string2Parse, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                return DateTime.MinValue;

            return parsedDate;
        }

        /// <summary> convert string to long </summary>
        /// <param name="string2Parse"></param>
        /// <returns></returns>
        internal static long String2Long(string string2Parse)
        {   // remove leading 0
            string2Parse = string2Parse.Trim();
            string2Parse = string2Parse.TrimStart('0');

            if (string2Parse.Length == 0)
                return 0;

            long parsedLong;
            return !long.TryParse(string2Parse, out parsedLong) ? 0 : parsedLong;
        }

        /// <summary> Convert passed string to argb color </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        [SuppressMessage("ReSharper", "ExceptionNotDocumentedOptional")]
        [SuppressMessage("ReSharper", "ExceptionNotDocumented")]
        public static ItxColor String2Color(string value)
        {
            if (value == @"         ")
                return null;

            return new ItxColor(255, Convert.ToByte(value.Substring(0, 3)),
                                   Convert.ToByte(value.Substring(3, 3)),
                                   Convert.ToByte(value.Substring(6, 3)));
        }

        ///// <summary> try to convert passed string to font </summary>
        ///// <param name="value"></param>
        ///// <returns></returns>
        //internal static ItxFont String2Font(string value)
        //{
        //    /* sample received values:
        //     * ARIAL UNICODE MS,400
        //     * COURIER NEW,400
        //     * 
        //     * [font family],[weight][quality]
        //     * 
        //     * font quality, based on getfontindirect - but ignored / not needed anymore with wpf
        //     * Default: DEFAULT_QUALITY (0)
        //     * Draft: DRAFT_QUALITY (1)
        //     * Proof: PROOF_QUALITY (2)
        //     * NonAntiAliased: NONANTIALIASED_QUALITY (3)
        //     * AntiAliased: ANTIALIASED_QUALITY (4)
        //     * ClearType: CLEARTYPE_QUALITY (5)
        //     * ClearTypeNatural: CLEARTYPE_NATURAL_QUALITY (6) */
        //    // split string
        //    string[] font2Parse = value.Split(',');
        //    if(font2Parse.Length != 2)
        //        return null;
            
        //    // build itxfont
        //    ItxFont itxFont = new ItxFont(font2Parse[0], font2Parse[1].Substring(0, 3));
        //    return itxFont;
        //}
    }
}